import pytz
import datetime
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from django.utils import timezone
from users.models import User


class DayActiveView(GenericAPIView):
    queryset = User.objects.filter(is_staff=False)
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0,
                                          tzinfo=pytz.timezone('Asia/Shanghai'))
        count = self.get_queryset().filter(last_login__gte=date_now).count()
        date = date_now.date()
        return Response({'count': count, 'date': date})


class DayOrdersView(GenericAPIView):
    queryset = User.objects.filter(is_staff=False)
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0,
                                          tzinfo=pytz.timezone('Asia/Shanghai'))
        count = self.get_queryset().filter(orders__create_time__gte=date_now).distinct().count()
        date = date_now.date()
        return Response({'count': count, 'date': date})


class MonthIncreView(GenericAPIView):
    queryset = User.objects.filter(is_staff=False)
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0,
                                          tzinfo=pytz.timezone('Asia/Shanghai'))
        date_begin = date_now - datetime.timedelta(days=29)
        data_list = []
        while date_begin <= date_now:
            date_end = date_begin + datetime.timedelta(days=1)
            count = self.get_queryset().filter(date_joined__gte=date_begin,
                                               date_joined__lt=date_end).count()
            date = date_begin.date()
            data_list.append({'count': count, 'date': date})
            date_begin += datetime.timedelta(days=1)
        return Response(data_list)
